<?php
/**
 * Created by PhpStorm.
 * User: lf
 * Date: 2018/1/15
 * Time: 18:07
 */
namespace ApiBundle\Controller;

use AppBundle\Service\lib\Aes;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Controller\BaseController;
use AppBundle\Entity\EntActive;

/**
 * Class ApiCommonController
 * @package ApiBundle\Controller
 */
class ApiCommonController extends BaseController{



    public function __construct(){
//        print_r($_SERVER);exit;
//        print_r($this->getParameter('headers_validate'));exit;
//        $this->checkHeaderInfo($_SERVER);
    }

    /**
     * @abstract 验证http请求的header头信息，
     * 请求头信息大致包含以下的内容sign 请求参数加密字符串  version app版本参数  app_type 应用平台参数
     * did 请求设备编码  model  设备型号
     * @param Request $request
     */
    public function checkHeaderInfo(Request $request){
        if($this->getParameter('headers_validate')){
            //获取请求头
            $_objHeader = $request->headers;
            //验证几个基础参数比如sign，did
            $t = $_objHeader->get('sign');
            if(empty($_objHeader->get('sign'))){//sign验签不存在
                return $this->get('common_service')->apiEnCode('0','sign不合法',[],400);
            }
            //验证设备号
            if(empty($_objHeader->get('did'))){//设备号不存在
                return $this->get('common_service')->apiEnCode('0','did数据不合法',[],400);
            }
            //校验sign和传递参数的值是否合法
            $_boolPass = $this->get('common_service')->checkSignPass($_objHeader);
            if($_boolPass){
                return $this->get('common_service')->apiEnCode('1','sign验证合法',[],200);
            }else{
                return $this->get('common_service')->apiEnCode('0','sign验证不合法',[],400);
            }
        }else{
            return $this->get('common_service')->apiEnCode('1','sign验证合法',[],200);
        }
    }


    /**
     * @abstract 验证是否有新的版本需要更新
     * @param Request $request
     * @Route("/validate/version",name="validate_version")
     */
    public function validateVersion(Request $request){
        //验证header头所带的信息是否合法
        $_strCheckInfo = $this->checkHeaderInfo($request);
        $_objCheckInfo = json_decode($_strCheckInfo);
        if($_objCheckInfo->status == 0){//header头数据验证失败
            $_strReturn = $this->get('common_service')->apiEnCode($_objCheckInfo->status,$_objCheckInfo->message,[],400);
        }else if($_objCheckInfo->status == 1){//header头数据验证成功
                //获取查询版本的类型参数
                $_arrCondition = $request->query->all();
                $_arrConditionTemp['status'] = 1;
                $_arrConditionTemp['apptype'] = $_arrCondition['app_type'];
                $_strVersion = $_arrCondition['version'];
                //查询的sql语句
                $_strSql = 'select version from AppBundle:EntVersion version where version.status = :status and version.appType = :apptype order by version.createTime desc';
                $em = $this->getDoctrine()->getManager();
                $_arrData = $em->getRepository('AppBundle:EntVersion')->getDataByConitionForVersion($_strSql,$_arrConditionTemp);
                //取出第一个数据
                $_objFirstData = array_shift($_arrData);
                //当前查询的存储此类型的更新包数据且更新包的版本大于目前请求客户端的版本
                if(is_object($_objFirstData) && $_objFirstData->getVersionCode() > $_strVersion){
                    $_arrReturn = array(
                        'version' => $_objFirstData->getVersion(),
                        'isforce' => $_objFirstData->getIsForce(),
                        'url' => $_objFirstData->getApkUrl()
                    );
                }else{//不用更新客户端
                    $_arrReturn = array(
                        'version' => $_arrConditionTemp['version'],
                        'isforce' => 0,
                        'url' => ''
                    );
                }
                //无论是否需要更新都要记录客户端初始化过程中
                $_objHeader = $request->headers;//获取header头
                $_objEntActive = new EntActive();
                $_objEntActive->setVersion($_objHeader->get('version'));
                $_objEntActive->setModel($_objHeader->get('model'));
                $_objEntActive->setDid($_objHeader->get('did'));
                $_objEntActive->setCreatetime(time());
                $em->persist($_objEntActive);
                $em->flush();
                //使用服务中的返回数据处理函数处理
                $_strReturn = $this->get('common_service')->apiEnCode('1','请求成功',$_arrReturn,200);
        }
        return new Response($_strReturn);
    }

    /**
     * @abstract 短信验证码的发送路由
     * @param Request $request
     * @Route("/validate/code/send",name="validate_code_send")
     */
    public function validateCodeSend(Request $request){
        //验证header头所带的信息是否合法
        $_strCheckInfo = $this->checkHeaderInfo($request);
        $_objCheckInfo = json_decode($_strCheckInfo);
        if($_objCheckInfo->status == 0) {//header头数据验证失败
            $_strReturn = $this->get('common_service')->apiEnCode($_objCheckInfo->status,$_objCheckInfo->message,[],400);
        }else if($_objCheckInfo->status == 1){
            //获取需要验证码短信发送的手机号码
            $_strPhone = $request->get('phone');
            //客户端传递的号码是经过加密处理的字符串，在实际使用之前先解密
            $_strPhone = $this->get('common_service')->decryptSign($_strPhone);
            $_strCode = $this->get('common_service')->get_code(4,1);//调用生成随机验证码
            $_strReturn = $this->get('common_service')->sendCodeSms($_strCode,$_strPhone);
        }
        return new Response($_strReturn);
    }

    /**
     * @abstract 后端加密路由
     * @Route("/endecrypt/back/text",name="endecrypt_back")
     */
    function endecryptTest(Request $request){
        //创建aes类对象
        $_objAes = new Aes();
        $_strEncrypt = $_objAes->cryptoJsAesEncrypt($_objAes->key,$request->get('encryptvalue'));
        return new Response($_strEncrypt);
    }


    /**
     * @abstract 测试接口,最后清理代码的时候可以不用删除，作为在线维护的入口
     * @Route("/validate/test",name="validate_test")
     */
    public function testVersion(){
        $_strCode = $this->get('common_service')->get_code(4,1);//调用生成随机验证码
        $this->get('common_service')->sendCodeSms($_strCode,'18963970962');
        print_r($_strCode);exit;
//        return $this->render('CommonBundle:Default:index.html.twig');
    }
}